// 获取时间
function getTime() {
    var myDate = new Date();
    var hour = myDate.getHours();
    var minute = myDate.getMinutes();
    if (hour < 10) hour = '0' + hour;
    if (minute < 10) minute = '0' + minute;
    return hour + ':' + minute;
}

//回车发送
document.onkeydown = keyDownSearch;

function keyDownSearch(e) {
    // 兼容FF和IE和Opera
    var theEvent = e || window.event;
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code == 13) {
        document.getElementById("send").click();
    }
    return true;
}

//点击发送文本
$('#send').click(function () {
    var content = $('#msg').val();
    if (content == '') {
        layer.msg('内容不能为空');
    } else {
        // 发送文本消息
        send_ws('chat_message', content, 0);
    }
});
//点击领取优惠券
$("#chat-list").on("click", "#lingqu", function (e) {
    if (config.role == 'staff') {
        layer.msg('只有客户可以领取优惠券哦');
        return false;
    }
    //领取券
    var chat_id = $(this).parents("li").attr('id');
    //console.log(chat_id);
    send_ws('receive_quan', chat_id);
});
//点击已领取的优惠券
$("#chat-list").on("click", "#lingqud", function (e) {
    if (config.role == 'staff') {
        layer.msg('只有客户可以领取优惠券哦');
        return false;
    }
    layer.msg('已领取');
});
// 监听输入改变发送按钮
$("#msg").bind('input porpertychange', function () {

    if ($("#msg").val().length > 0) {
        $(".layim-send").removeClass('layui-disabled');
    } else {
        $(".layim-send").addClass('layui-disabled');
    }
});
// 点击券
$('#up-quan').click(function (e) {
    e.stopPropagation();
    if (1 == quan_flag) {
        showQuan();
        $('#quan-box').show();
        quan_flag = 2;
        $('#face-box').hide();
        flag = 1;
    } else {
        $('#quan-box').hide();
        quan_flag = 1;
    }
});

// 展示券
function showQuan() {
    $.ajax({
        type: 'POST',
        url: '/human/web.chat/get_quan',
        data: {shop_id: config.shop_id},
        success: function (res) {
            if (res.code == 0) {
                var quan_list = res.data;
                var _html = '<ul class="layui-layim-quan">';
                var quan_index = 1;
                for (var i in quan_list) {
                    _html += '<li onclick="checkQuan(this)" title="' + quan_list[i].coupon_title + '" data-zhekou="' + quan_list[i].zhekou + '" id="' + quan_list[i].coupon_id + '">' + quan_index + '.' + quan_list[i].coupon_title + '</li>';
                    quan_index++;
                }
                _html += '</ul>';

                document.getElementById('quan-box').innerHTML = _html;
            }
        },
        dataType: 'json'
    });
}

// 选择券
function checkQuan(obj) {
    var zhekou = $("#" + obj.id + "").attr("data-zhekou");
    document.getElementById('quan-box').style.display = 'none';
    $(".layim-send").removeClass('layui-disabled');
    quan_flag = 1;
    quan_info = {
        quan_id: obj.id,
        title: obj.title,
        zhekou: zhekou,
        to_user_id: config.to_user_id,
        vouchers_id: 0,
        is_receive: 0
    };
    send_ws('chat_message', quan_info, 2);
}

// 点击表情
$('#up-face').click(function (e) {
    e.stopPropagation();
    if (1 == flag) {
        showFaces();
        $('#face-box').show();
        flag = 2;
        $('#quan-box').hide();
        quan_flag = 1;
    } else {
        $('#face-box').hide();
        flag = 1;
    }
});
// 监听点击旁边关闭表情
document.addEventListener("click", function () {
    if (2 == flag) {
        document.getElementById('face-box').style.display = 'none';
        flag = 1;
    }
});

// 展示表情数据
function showFaces() {
    var alt = getFacesIcon();
    var _html = '<ul class="layui-layim-face">';
    var len = alt.length;
    for (var index = 0; index < len; index++) {
        _html += '<li title="' + alt[index] + '" onclick="checkFace(this)"><img src="/chat/service/images/face/' + index + '.gif" /></li>';
    }
    _html += '</ul>';

    document.getElementById('face-box').innerHTML = _html;
}

// 选择表情
function checkFace(obj) {
    var msg = document.getElementById('msg').value;
    document.getElementById('msg').value = msg + ' face' + obj.title + ' ';
    document.getElementById('face-box').style.display = 'none';
    $(".layim-send").removeClass('layui-disabled');
    flag = 1;
}

// 图片 文件上传
layui.use(['upload'], function () {
    var upload = layui.upload;

    // 执行实例
    var uploadInstImg = upload.render({
        elem: '#up-image' // 绑定元素
        , accept: 'images'
        , exts: 'jpg|jpeg|png|gif'
        , url: '/human/api.upload/upload_img' // 上传接口
        , data: {type: 'chat'}
        , done: function (res) {
            // 发送图片
            send_ws('chat_message', res.data.src, 1)
        }
        , error: function () {
            // 请求异常回调
        }
    });

    $('.layui-upload-file').hide();
});


/**
 *展示消息
 **/
function chatAppend(acceptData) {
    var content = null;
    if (acceptData.content == '') {
        return false;
    }
    if (acceptData.types == 1) {
        content = "img[" + acceptData.content + "]";
    } else if (acceptData.types == 2) {
        if (typeof acceptData.content == 'string') {
            quan_info = eval("(" + acceptData.content + ")");
        } else {
            quan_info = acceptData.content;
        }
        content = "quan[xxxxxx]";
    } else {
        content = acceptData.content;
    }
    content = replaceContent(content);
    var _html = '<li class="layim-chat-system"><span>' + acceptData.create_time + '</span></li>';
    if (acceptData.user_id == config.user_id) {
        /* 自己的消息*/
        _html += '<li class="layim-chat-li layim-chat-mine" id="' + acceptData.id + '">' +
            '<div class="layim-chat-user">' +
            '<img src="' + acceptData.head_img + '">' +
            '<cite>我</cite>' +
            '</div>' +
            '<div class="layim-chat-text">' + content + ' </div>' +
            '</li>';
    } else {
        /*别人的消息*/
        _html += '<li class="layim-chat-li" id="' + acceptData.id + '">' +
            '<div class="layim-chat-user">' +
            '<img src="' + acceptData.head_img + '">' +
            '<cite>' + acceptData.username + '</cite>' +
            '</div>' +
            '<div class="layim-chat-text">' + content + '</div>' +
            '</li>';
    }
    $('#chat-list').append(_html);
    //滚动到底部
}

//退出
$('#logout-btn').click(function () {
    loginOut();
});

// 退出
function loginOut() {
    window.history.go(-1);
}

// 转义聊天内容中的特殊字符
function replaceContent(content) {
    // 支持的html标签
    var html = function (end) {
        return new RegExp('\\n*\\[' + (end || '') + '(pre|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\]\\n*', 'g');
    };
    content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
        .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') // XSS
        .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') // 转义@

        .replace(/face\[([^\s\[\]]+?)\]/g, function (face) {  // 转义表情
            var alt = face.replace(/^face/g, '');
            return '<img alt="' + alt + '" title="' + alt + '" src="' + faces[alt] + '">';
        })
        .replace(/quan\[([^\s]+?)\]/g, function () {  // 转义优惠券
            var html = '<div class="layim-chat-quan">';
            html += '<div class="layim-chat-quan-title">' + quan_info.title + '</div>';
            html += '<div class="layim-chat-quan-zhekou">' + quan_info.zhekou + '</div>';
            if (quan_info.is_receive == 1) {
                html += '<div class="layim-chat-quan-lingqu"><button id="lingqud">已领取优惠券</button></div>';
            } else {
                html += '<div class="layim-chat-quan-lingqu"><button id="lingqu" >领取优惠券</button></div>';
            }

            html += ' </div>';
            return html;
        })
        .replace(/img\[([^\s]+?)\]/g, function (img) {  // 转义图片
            return '<img class="layui-whisper-photos" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '" width="100px" height="100px">';
        })
        .replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function (str) { // 转义文件
            var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
            var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
            if (!href) return str;
            return '<a class="layui-whisper-file" href="' + href + '" download target="_blank"><i class="layui-icon">&#xe61e;</i><cite>' + (text || href) + '</cite></a>';
        })
        .replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function (str) { // 转义链接
            var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
            var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
            if (!href) return str;
            return '<a href="' + href + '" target="_blank">' + (text || href) + '</a>';
        }).replace(html(), '\<$1 $2\>').replace(html('/'), '\</$1\>') // 转移HTML代码
        .replace(/\n/g, '<br>') // 转义换行
    return content;
};

// 表情替换
var faces = function () {
    var alt = getFacesIcon(), arr = {};
    layui.each(alt, function (index, item) {
        arr[item] = '/chat/service/js/layui/images/face/' + index + '.gif';
    });
    return arr;
}();

// 表情对应数组
function getFacesIcon() {
    return ["[微笑]", "[嘻嘻]", "[哈哈]", "[可爱]", "[可怜]", "[挖鼻]", "[吃惊]", "[害羞]", "[挤眼]", "[闭嘴]", "[鄙视]",
        "[爱你]", "[泪]", "[偷笑]", "[亲亲]", "[生病]", "[太开心]", "[白眼]", "[右哼哼]", "[左哼哼]", "[嘘]", "[衰]",
        "[委屈]", "[吐]", "[哈欠]", "[抱抱]", "[怒]", "[疑问]", "[馋嘴]", "[拜拜]", "[思考]", "[汗]", "[困]", "[睡]",
        "[钱]", "[失望]", "[酷]", "[色]", "[哼]", "[鼓掌]", "[晕]", "[悲伤]", "[抓狂]", "[黑线]", "[阴险]", "[怒骂]",
        "[互粉]", "[心]", "[伤心]", "[猪头]", "[熊猫]", "[兔子]", "[ok]", "[耶]", "[good]", "[NO]", "[赞]", "[来]",
        "[弱]", "[草泥马]", "[神马]", "[囧]", "[浮云]", "[给力]", "[围观]", "[威武]", "[奥特曼]", "[礼物]", "[钟]",
        "[话筒]", "[蜡烛]", "[蛋糕]"]
}